<?php

namespace app\queue;

use app\constant\CommonConstant;
use app\model\PixelLogs;
use app\service\pixel\FaceBookPixelTrack;
use think\queue\Job;

class PixelTrackQueue
{
    public function fire(Job $job, $data)
    {
        // 获取当前尝试次数
        $attempts = $job->attempts();
        echo "开始处理任务第{$attempts}: ".date('Y-m-d H:i:s')."\n";
        $log = PixelLogs::createTrackLog($data);
        // 业务处理逻辑
        try {
            if(!$log) throw new \Exception("日志不存在");
            if($log->platform == CommonConstant::TRAFFIC_SOURCE_TK) throw new \Exception("不支持TK追踪");
            $service = new FaceBookPixelTrack();
            if($log->event_type == CommonConstant::FB_EVENT_PREVIEW){
                $service->Track_view($log);
            }else{
                $service->Track_purchase($log);
            }
            // 任务执行成功
            $job->delete();
            echo "任务处理完成\n";

        } catch (\Exception $e) {
            dump($e);
            if($attempts <= 3){
                // 指数退避策略：重试延迟时间逐渐增加（2,4,8秒）
                $delay = pow(2, $attempts);
                echo "任务处理失败，第 {$attempts} 次重试，延迟 {$delay} 秒\n";
                $job->release($delay);
            } else {
                $job->delete();
                throw $e;
            }
        }
    }

    public function failed($data,$e){

    }
}